package org.yanghaokun.org.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yanghaokun.basic.service.impl.BaseServiceImpl;
import org.yanghaokun.basic.util.MD5Utils;
import org.yanghaokun.basic.util.StrUtils;
import org.yanghaokun.org.domain.Employee;
import org.yanghaokun.org.mapper.EmployeeMapper;
import org.yanghaokun.org.service.IEmployeeService;
import org.yanghaokun.user.domain.LoginInfo;
import org.yanghaokun.user.mapper.LoginInfoMapper;

import java.util.List;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LoginInfoMapper loginInfoMapper;

    //Employee需要同步操作loginInfo
    @Transactional
    @Override
    public void add(Employee employee) {
        //我们在添加员工信息的时候我们需要初始化盐值和密码
        initEmployee(employee);
        //然后我们将员工信息转变为loginInfo
        LoginInfo info = employee2LoginInfo(employee);
        //转换完了之后我们直接将info对象存入数据库
        loginInfoMapper.save(info);
        //将info对象和员工关联
        employee.setLogininfo(info);
        //将员工保存
        employeeMapper.save(employee);

    }

    private LoginInfo employee2LoginInfo(Employee employee) {
        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(employee,loginInfo);
        //将info对象设置为员工类型
        loginInfo.setType(0);//0 是员工 1 用户
        return loginInfo;
    }

    private void initEmployee(Employee employee) {
        //这里是将数据进行初始化
        String salt = StrUtils.getComplexRandomString(32);
        String sercuityPwd = MD5Utils.pwdByMd5(employee.getPassword() + salt);

        employee.setSalt(salt);
        employee.setPassword(sercuityPwd);
    }

    @Override
    public void bulkDel(List<Long> ids) {
        employeeMapper.bulkDel(ids);
    }

    @Override
    public void del(Long id) {
        //通过员工id查询Employee进而获取loginInfoid
        Employee employee = employeeMapper.findOne(id);
        //删除loginInfo
        loginInfoMapper.delete(employee.getLogininfo_id());
        //删除员工
        employeeMapper.delete(id);
    }

    @Override
    public void update(Employee employee) {
        super.update(employee);
    }
}
